package com.attendance.www.hr.service.impl;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.UserBean;
import com.attendance.www.hr.beans.UserEmployeeBean;
import com.attendance.www.hr.constant.AppConstant;
import com.attendance.www.hr.dao.mapper.EmployeeMapper;
import com.attendance.www.hr.dao.mapper.LinkAddressMapper;
import com.attendance.www.hr.dao.mapper.SystemConfigureMapper;
import com.attendance.www.hr.dao.mapper.UserExtMapper;
import com.attendance.www.hr.dao.mapper.UserLoginMapper;
import com.attendance.www.hr.dao.mapper.UserMapper;
import com.attendance.www.hr.entitys.Employee;
import com.attendance.www.hr.entitys.EmployeeExample;
import com.attendance.www.hr.entitys.LinkAddress;
import com.attendance.www.hr.entitys.LinkAddressExample;
import com.attendance.www.hr.entitys.User;
import com.attendance.www.hr.entitys.UserExample;
import com.attendance.www.hr.entitys.UserExample.Criteria;
import com.attendance.www.hr.entitys.UserLogin;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IApprovalService;
import com.attendance.www.hr.service.IUserService;
import com.attendance.www.hr.utils.CSRFTokenUtil;
import com.zhangkongli.frame.utils.MD5Util;

@Service
public class UserServiceImpl implements IUserService{
	
	@Resource
	private UserMapper userDao;
	@Resource
	private UserExtMapper userExtDao;
	@Resource
	private EmployeeMapper employeeDao;
	@Resource
	private UserLoginMapper userLoginDao;
	@Resource
	private SystemConfigureMapper systemConfigureDao;
	@Resource
	private LinkAddressMapper linkAddressDao;
	@Resource
	private IApprovalService approvalService;
	
	
	@Override
	public boolean getVerificationPassword(UserBean userBean){
		//获取初始化密码
		MD5Util md5 = new MD5Util();
		String mdPassWord = md5.getMD5ofStr(AppConstant.PASSWORD);
		Date currentDate = new Date(); 
		UserBean userLogin=userExtDao.getUserlogin(userBean.getUserName(), currentDate, currentDate);
	    if(userLogin!=null){
	    	if(userLogin.getEmployeeId()!=null){
	    		Employee employee=employeeDao.selectByPrimaryKey(userLogin.getEmployeeId());
		    	if(employee!=null){
		    		if(employee.getEmployeeIsSeparated()==1){
		    			throw new ResultFaultException("1_00004");
		    		}
		    	}
	    	}
	    	//处理登陆密码
	    	String loginPassWord=md5.getMD5ofStr(userBean.getPassword());
	    	if(StringUtils.isNotBlank(userLogin.getPassword())){
	    		//判断登录密码和原有密码，并且等于初始化密码
				if(userLogin.getPassword().equals(loginPassWord) && userLogin.getPassword().equals(mdPassWord)){
					return true;
				}else{
					return false;
				}
			}else{
				throw new ResultFaultException("1_00005");
			}
	    }else{
	    	throw new ResultFaultException("1_00002");
	    }
	}

	/**
	 * 用户登录
	 * @return
	 */
	@Override
	public Integer login(UserBean userBean) {
		//获取系统当前时间
		Date currentDate = new Date(); 
		UserBean userLogin=userExtDao.getUserlogin(userBean.getUserName(), currentDate, currentDate);
	    if(userLogin!=null){
	    	if(userLogin.getEmployeeId()!=null){
	    		Employee employee=employeeDao.selectByPrimaryKey(userLogin.getEmployeeId());
		    	if(employee!=null){
		    		if(employee.getEmployeeIsSeparated()==1){
		    			throw new ResultFaultException("1_00004");
		    		}
		    	}
	    	}
	    	MD5Util md5 = new MD5Util();
			String mdPassWord=md5.getMD5ofStr(userBean.getPassword());
	    	//String mdPassWord=userBean.getPassword().toUpperCase();
			if(StringUtils.isNotBlank(userLogin.getPassword())){
				if(userLogin.getPassword().equals(mdPassWord)){
					return userLogin.getUserId();
				}else{
					throw new ResultFaultException("1_00003");
				}
			}else{
				throw new ResultFaultException("1_00005");
			}
	    }else{
	    	throw new ResultFaultException("1_00002");
	    }
	}
	
	/**
	 * 返回登录用户
	 * @return
	 */
	@Override
	public UserEmployeeBean getUserEmployee(Integer userId,String ip){
		UserEmployeeBean userEmployee=new UserEmployeeBean();
		UserExample example=new UserExample();
		example.createCriteria().andUserIdEqualTo(userId);
		//查询登陆用户信息
		List<User> userList=userDao.selectByExample(example);
		if(userList!=null){
			User user=userList.get(0);
			userEmployee.setUserId(user.getUserId());
			userEmployee.setPrivilegeGroupId(user.getPrivilegeGroupId());
			userEmployee.setUserName(user.getUsername());
			userEmployee.setToken(CSRFTokenUtil.generate());
			if(user.getEmployeeId()!=null){
				Employee employee=employeeDao.selectByPrimaryKey(user.getEmployeeId());
				userEmployee.setEmployeeId(employee.getEmployeeId());
				userEmployee.setEmployeeNo(employee.getEmployeeNo());
				userEmployee.setChineseName(employee.getChineseName());
				userEmployee.setEnglishName(employee.getEnglishName());
				userEmployee.setSex(employee.getSex());
				userEmployee.setEmail(employee.getEmail());
				userEmployee.setEmployeeIsSeparated(employee.getEmployeeIsSeparated());
				userEmployee.setEmployeeSeparatedDate(employee.getEmployeeSeparatedDate());
				userEmployee.setEmployeeType(employee.getEmployeeType());
				userEmployee.setEmployeeCategory(employee.getEmployeeCategory());

				//添加IP地址
				UserLogin userLogin=new UserLogin();
				userLogin.setEmployeeId(employee.getEmployeeId());
				userLogin.setIp(ip);
				userLoginDao.insertSelective(userLogin);
			}
		}	
		return userEmployee;
	}
	
	@Override
	public User validateUser(UserBean userBean) {
		UserExample example = new UserExample();
		Criteria criter = example.createCriteria();
		if (StringUtils.isNotBlank(userBean.getUserName())) {
			criter.andUsernameEqualTo(userBean.getUserName());
		}
		if (StringUtils.isNotBlank(userBean.getPassword())) {
			MD5Util md5 = new MD5Util();
			String mdPassWord = md5.getMD5ofStr(userBean.getPassword());
			criter.andPasswordEqualTo(mdPassWord);
		}
		List<User> userList = userDao.selectByExample(example);
		if (userList.size() > 0) {
			return userList.get(0);
		} else {
			throw new ResultFaultException("1_00006");
		}
	}

	@Override
	public void updateUserPassWord(User user) {
		MD5Util md5 = new MD5Util();
		String mdPassWord = md5.getMD5ofStr(user.getPassword());
		user.setPassword(mdPassWord);
		user.setUpdateTime(new Date());
		userDao.updateByPrimaryKey(user);
	}
	
	/**
	 * 忘记密码
	 */
	@Override
	public boolean forgetPassword(String mail) {
		//验证邮箱是否存在
		EmployeeExample employeeExample=new EmployeeExample();
		employeeExample.createCriteria().andEmailEqualTo(mail);
		List<Employee> employeeList=employeeDao.selectByExample(employeeExample);
		//表示邮箱错误
		if(employeeList.size()<=0) {
			throw new ResultFaultException("0_00033");
		}else {
			Employee employee = employeeList.get(0);
			
			approvalService.sendEmail(employee.getEmployeeId(), "重置密码", null, null);
			
	        /*Date nowDate = new Date();
	        long now = nowDate.getTime();
	        String str = now + employee.getEmail();
	        MD5Util md5 = new MD5Util();
			String key=md5.getMD5ofStr(str);
			
			//把key(密钥)写入数据库地址表
			LinkAddress linkAddress = new  LinkAddress();
			linkAddress.setEmployeeId(employee.getEmployeeId());
			linkAddress.setUrlKey(key);
			linkAddress.setType(0);//0，是忘记密码
			linkAddressDao.insertSelective(linkAddress);
			//发邮件
			SystemConfigure systemConfigure=systemConfigureDao.selectByPrimaryKey(1);
			if(MailUtils.send(systemConfigure, mail, AppConstant.MAIL_TITLE,
					"点击链接地址重置登录密码"+AppConstant.MAIL_FORGET_PASSWORD_CONTENT+ key +"\">重置用户密码</a>", AppConstant.MAIL_ENDING)) {
			}else {
				return false;
			}*/
			return true;
		}
	}

	/**
	 * 验证链接是否有效(key)
	 * 0密码，1审批 有效，null 无效
	 */
	@Override
	public Integer checkKey(String key) {
		LinkAddressExample laExample = new LinkAddressExample();
		laExample.createCriteria().andUrlKeyEqualTo(key);
		List<LinkAddress> laList = linkAddressDao.selectByExample(laExample);
		if (laList.size()>0) {//有数据
			//判断类型
			LinkAddress linkAddress = laList.get(0);
			if (linkAddress.getType()==0) {//密码
				//24小时失效判断
				Date createDate = linkAddress.getCreateTime();
				createDate = DateUtils.addDays(createDate, 1);
				if (createDate.after(new Date())) {
					return 0;
				}
			} else {
				return 1;
			}
		}
		return null;
	}

	/**
	 * 获取登陆人userid
	 */
	@Override
	public Integer getUserId(String key) {
		LinkAddressExample laExample = new LinkAddressExample();
		laExample.createCriteria().andUrlKeyEqualTo(key);
		List<LinkAddress> laList = linkAddressDao.selectByExample(laExample);
		LinkAddress linkAddress = laList.get(0);
		Integer employeeId = linkAddress.getEmployeeId();
		
		UserExample userExample =  new UserExample();
		userExample.createCriteria().andEmployeeIdEqualTo(employeeId)
		.andThruDateIsNull();
		List<User> userList = userDao.selectByExample(userExample);
		
		return userList.get(0).getUserId();
	}

	/**
	 * 邮件重置密码
	 */
	@Override
	public boolean doResetPassword(String newPasswd, String key) {
		Integer userId = this.getUserId(key);
		//处理登陆密码
		MD5Util md5 = new MD5Util();
		String loginPassWord=md5.getMD5ofStr(newPasswd);
    	User user = new User();
    	user.setUserId(userId);
		user.setPassword(loginPassWord);
		userDao.updateByPrimaryKeySelective(user);
		//删除link地址
		LinkAddressExample linkExample = new LinkAddressExample();
		linkExample.createCriteria().andUrlKeyEqualTo(key);
		linkAddressDao.deleteByExample(linkExample);
		return true;
	}
	
	/**
	 * 登录
	 * @param userBean
	 * @return
	 */
	@Override
	public Integer getUserByUserBean(UserBean userBean) {
		UserExample userExample=new UserExample();
		userExample.createCriteria().andUsernameEqualTo(userBean.getUserName());
		List<User> userList=userDao.selectByExample(userExample);
	    if(userList.size()>0){
		    return userList.get(0).getUserId();
	    }
	    else {
	    	return null;
	    }
	}
}
